package com.ssm.demo.service.impl;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssm.demo.dao.TUserMapper;
import com.ssm.demo.pojo.TStudent;
import com.ssm.demo.pojo.TUser;
import com.ssm.demo.pojo.TUserExample;
import com.ssm.demo.service.TUserService;
import com.ssm.demo.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Zhang Yu
 * @description: TODO
 * @date 2024/4/2 7:42
 */
@Service
@Slf4j
public class TUserServiceImpl implements TUserService {
    @Autowired
    private TUserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Map<String,Object> login(TUser user) {
        Example example=new Example(TUser.class);
        Example.Criteria c1=example.createCriteria();
        c1.andEqualTo(user);
        TUser resultUser = userMapper.selectOne(user);
        System.out.println("resultUser is " + resultUser);
        // 根据接收用户名密码查询数据库
        if (resultUser!=null){
            Map<String,Object> map = new HashMap<>();
            Map<String, String> payload = new HashMap<>();
            payload.put("id",resultUser.getId().toString());
            payload.put("name",resultUser.getName());
            // 生成jwt令牌
            String token = JWTUtils.getToken(payload);
            map.put("state",true);
            map.put("msg","登录成功！");
            map.put("token",token);  // 响应token
            redisTemplate.opsForValue().set("user:"+resultUser.getId(), token, 7, TimeUnit.DAYS);
            return map;
        }
        throw  new RuntimeException("登录失败 -.-");
    }

    public Map<String,Object> verify(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        log.info("当前token为：[{}]",token);
        Map<String,Object> map = new HashMap<>();
        try {
            // 验证令牌
            DecodedJWT verify = JWTUtils.verify(token);
            map.put("state",true);
            map.put("msg","请求成功");
            return map;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效签名！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效！");
        }
        map.put("state",false);
        return map;
    }

    @Override
    public Map<String, Object> detailUser(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        // 获取请求头中令牌
        String token = request.getHeader("Authorization");
        try {
            // 验证令牌
            DecodedJWT decodedJwt = JWTUtils.verify(token);
            String userId = decodedJwt.getClaim("id").asString();
            Boolean redisResult = redisTemplate.hasKey("user:" + userId);
            if (!redisResult) {
                map.put("code", 401);
                map.put("msg","Invalid Token");
                map.put("state",false);  // 设置状态
            }else {
                TUser tUser = new TUser().setId(Integer.valueOf(userId));
                TUser resultUser = userMapper.selectOne(tUser);
                map.put("code", 200);
                map.put("name", resultUser.getName());
            }

        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg","无效签名！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg","算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg","token无效！");
        }
        return map;
    }
}
